package com.maxlen.coupon.listener;

import com.maxlen.common.rabbitMQConstant.CouponRabbitMQConstant;
import com.maxlen.coupon.entity.to.CouponLockTO;
import com.maxlen.coupon.service.CouponHistoryService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@RabbitListener(queues = CouponRabbitMQConstant.COUPON_COUPON_RELEASE_QUEUE)
public class CouponReleaseQueueListener {

    @Autowired
    private CouponHistoryService couponHistoryService;

    @RabbitHandler
    public void couponCouponReleaseQueue(CouponLockTO couponLockTO, @Headers Message headers, Channel channel) throws IOException {
        log.info("返还优惠券: {}", couponLockTO);
        try{
            couponHistoryService.unlockCoupon(couponLockTO);
            channel.basicAck(headers.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            log.info(e.getMessage());
            channel.basicReject(headers.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void couponCouponReleaseQueue(byte[] orderSn, @Headers Message headers, Channel channel) throws IOException {
        log.info("订单取消, 通过订单号: {} 返还优惠券.....", new String(orderSn));
        try{
            couponHistoryService.unlockCoupon(new String(orderSn));
            channel.basicAck(headers.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            log.info(e.getMessage());
            channel.basicReject(headers.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
